Add Weekly Financial Report functionality with repository and tests - #65
Conversation
- Introduced `formatCurrency` function to format numbers as USD currency, ensuring proper localization and rounding. - Added `getRateByDate` function to retrieve rates from a historical dataset based on a specified date, with handling for undefined inputs and edge cases. - Created unit tests for both functions to validate their functionality and accuracy, covering various scenarios for currency formatting and rate retrieval. These additions enhance the utility functions for financial calculations and improve test coverage for the application.
- Updated the `getRateByDate` function to sort the rate history dates chronologically using a custom sorting function. This ensures that the dates are processed in the correct order, improving the accuracy of rate retrieval based on date. These changes enhance the functionality of the rate retrieval process, ensuring more reliable data handling.
- Introduced `WeeklyFinancialReportRepository` class implementing `IWeeklyFinancialReportRepository` for generating weekly financial reports based on target units, employees, and projects. - Added `IWeeklyFinancialReportRepository` interface and `GenerateReportInput` type for structured input handling. - Created unit tests for the repository to validate report generation, ensuring correct summary and details output for various input scenarios, including handling of empty input arrays. These changes enhance the financial reporting capabilities of the application, providing structured and detailed insights into weekly performance.
📝 Walkthrough""" WalkthroughThis change introduces a weekly financial report generation feature. It adds an interface for the report repository, an implementation that aggregates and summarizes financial data by group, and comprehensive unit tests. Supporting utility classes for aggregation, marginality calculation, and formatting are included. The module is exported via an index file, enabling use of the report generation functionality elsewhere in the codebase. Changes
Sequence Diagram(s)sequenceDiagram
participant Caller
participant WeeklyFinancialReportRepository
participant GroupAggregator
participant MarginalityCalculator
participant WeeklyFinancialReportFormatter
Caller->>WeeklyFinancialReportRepository: generateReport({targetUnits, employees, projects})
WeeklyFinancialReportRepository->>GroupAggregator: aggregateGroup(targetUnits, groupId)
WeeklyFinancialReportRepository->>MarginalityCalculator: calculate(revenue, cogs)
WeeklyFinancialReportRepository->>WeeklyFinancialReportFormatter: formatDetail(...)
WeeklyFinancialReportRepository->>WeeklyFinancialReportFormatter: formatSummary(...)
WeeklyFinancialReportRepository->>WeeklyFinancialReportFormatter: formatFooter(totalHours)
WeeklyFinancialReportRepository->>Caller: Return { summary, details }
Possibly related PRs
Suggested reviewers
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms (6)
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
🔍 Vulnerabilities of
|
| digest | sha256:0b3972d8faafb0c10b944a8c40ae50c05e2c45b95aebaf2d42202ad91c48edba |
| vulnerabilities | |
| platform | linux/amd64 |
| size | 243 MB |
| packages | 1628 |
📦 Base Image node:20-alpine
Description
Description
| ||||||||||||||||
Description
| ||||||||||||||||
Description
| ||||||||||||||||
Description
| ||||||||||||||||
Description
| ||||||||||||||||
Description
| ||||||||||||||||
Description
| ||||||||||||||||
Description
|
killev
left a comment
There was a problem hiding this comment.
the generate function looks too complicated, it requires it enable ESLint rules that tracks complexity as separate PR.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
workers/main/src/services/WeeklyFinancialReport/index.ts (1)
1-1: Re-export the interface for downstream consumersOnly the repository class is re-exported. Call-sites that depend on the
GenerateReportInputtype or theIWeeklyFinancialReportRepositoryinterface will still have to reach into the sub-path, defeating the purpose of an index barrel.export * from './WeeklyFinancialReportRepository'; +export * from './IWeeklyFinancialReportRepository';workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.test.ts (1)
50-63: Broaden test assertions to validate numeric accuracyThe test only checks that strings are non-empty and contain certain keywords. A regression could silently alter the underlying maths (e.g., margin calculation) yet still pass. Consider asserting at least one concrete figure (e.g., expected total revenue for Group A).
workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.ts (1)
108-108: Legend string has unbalanced spacingMinor formatting nit: double spaces after the yellow-circle entry look like a typo.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
workers/main/src/services/WeeklyFinancialReport/IWeeklyFinancialReportRepository.ts(1 hunks)workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.test.ts(1 hunks)workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.ts(1 hunks)workers/main/src/services/WeeklyFinancialReport/index.ts(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
workers/main/src/services/WeeklyFinancialReport/IWeeklyFinancialReportRepository.ts (2)
workers/main/src/common/types.ts (1)
TargetUnit(3-14)workers/main/src/services/FinApp/types.ts (2)
Employee(5-12)Project(14-25)
⏰ Context from checks skipped due to timeout of 90000ms (4)
- GitHub Check: Docker Security Scanning (n8n, Dockerfile.n8n, n8n-test:latest)
- GitHub Check: Docker Security Scanning (temporal, Dockerfile.temporal, temporal-test:latest)
- GitHub Check: Service Availability Check
- GitHub Check: SonarQube
🔇 Additional comments (2)
workers/main/src/services/WeeklyFinancialReport/IWeeklyFinancialReportRepository.ts (1)
1-2: Verify import path correctness
EmployeeandProjectare imported from../FinApp. In the current tree the concrete types appear to live inFinApp/types.ts; unless../FinApp/index.tsre-exports them, this will be a path error at build time.Would you double-check the FinApp barrel exports or adjust the import to
../FinApp/typesif necessary?workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.ts (1)
80-91: Negative or NaN marginality edge-case
groupMarginalityPercentis derived from revenue; if revenue is0but COGS is non-zero the percent is forced to0, categorising it as low marginality. Consider flagging explicitly impossible/invalid data instead of silently labelling.
- Added `HIGH_MARGINALITY_THRESHOLD` and `MEDIUM_MARGINALITY_THRESHOLD` constants to define marginality levels. - Introduced `GroupAggregator` class for aggregating target units by group and calculating total hours. - Implemented `MarginalityCalculator` class to calculate marginality metrics based on revenue and COGS. - Created `WeeklyFinancialReportFormatter` class for formatting report details and summaries. - Updated `WeeklyFinancialReportRepository` to utilize new classes for processing target units and generating reports. These changes improve the financial reporting capabilities by providing structured aggregation and calculation of marginality, enhancing the overall reporting process.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.ts (2)
33-44: InjectcurrentDatefor deterministic testsPrior review feedback highlighted that grabbing
new Date()internally hinders reproducible tests. Accept it as an optional parameter with a default to keep runtime ergonomics unchanged.- async generateReport({ - targetUnits, - employees, - projects, - }: GenerateReportInput) { - const currentDate = new Date(); + async generateReport( + { targetUnits, employees, projects }: GenerateReportInput, + currentDate: Date = new Date(), + ) {
48-62: Quadratic complexity caused by repeated filteringInside the loop we call
GroupAggregator.aggregateGroup, which performsArray.filterover alltargetUnitsfor every distinct group. Withggroups andnunits this degrades to O(n × g) (worst-case O(n²)).Pre-group once with a
Map:- for (const targetUnit of targetUnits) { - this.processTargetUnit({ … }); - } + const grouped = new Map<number, TargetUnit[]>(); + for (const unit of targetUnits) { + (grouped.get(unit.group_id) ?? grouped.set(unit.group_id, []).get(unit.group_id)!).push(unit); + } + + for (const [_, groupUnits] of grouped) { + this.processTargetUnit({ + targetUnit: groupUnits[0], // representative for meta‐data + targetUnits: groupUnits, + … // rest unchanged, drop processedGroupIds + }); + }You’ll also be able to delete the
processedGroupIdsset entirely.
🧹 Nitpick comments (6)
workers/main/src/services/WeeklyFinancialReport/GroupAggregator.ts (1)
3-15: Prefer a plain function over a static-only classThe class hosts only one static method and no state. Keeping it as a class introduces needless ceremony and violates the no-static-only-class rule flagged by Biome. A small utility function exported from the module would be simpler to tree-shake and test.
-export class GroupAggregator { - static aggregateGroup(targetUnits: TargetUnit[], targetUnitId: number) { - … - return { groupUnits, groupTotalHours }; - } -} +export function aggregateGroup( + targetUnits: TargetUnit[], + targetUnitId: number, +) { + … + return { groupUnits, groupTotalHours }; +}Update the import sites accordingly.
workers/main/src/services/WeeklyFinancialReport/MarginalityCalculator.ts (2)
19-47: Static-only class &thisusage can be flattenedSame as above, the calculator is purely functional. You can export three top-level functions (
calculate,classify,getIndicator) and theenum. This removes the surprisingthis.classify/this.getIndicatorcalls that Biome warns about and avoids potential confusion when the class name is minified.
36-45: Redundantcase MarginalityLevel.LowBecause the
defaultbranch already returns the same value, the explicitLowcase is superfluous.- case MarginalityLevel.Low: - return ':arrowdown:'; - default: - return ':arrowdown:'; + default: + return ':arrowdown:';workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportFormatter.ts (2)
7-12: Interface name violates PascalCase convention
formatSummaryInputis the only interface in the codebase that starts with a lowercase letter; this stands out and breaks TS/ESLint naming rules.-export interface formatSummaryInput { +export interface FormatSummaryInput {Remember to update the type at the call-site in
formatSummary.
25-41: Static field with arrow function is unnecessaryDeclaring
static formatDetail = (...) =>creates a class field and incurs an extra property lookup compared with a regular static method. Change to a standard static method unless you intentionally need lexicalthis.- static formatDetail = ({ + static formatDetail({ … }: FormatDetailInput) { return ( … ); - => + }workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.ts (1)
153-170: Date arithmetic is hard to reason aboutThe opaque magic numbers
- ((getDay() + 6) % 7) - 7make maintenance tricky. Consider extracting this into a small helpergetPreviousWeekRange(date)that clearly communicates intent and can be unit-tested.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
workers/main/src/configs/weeklyFinancialReport.ts(1 hunks)workers/main/src/services/WeeklyFinancialReport/GroupAggregator.ts(1 hunks)workers/main/src/services/WeeklyFinancialReport/IWeeklyFinancialReportRepository.ts(1 hunks)workers/main/src/services/WeeklyFinancialReport/MarginalityCalculator.ts(1 hunks)workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportFormatter.ts(1 hunks)workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.ts(1 hunks)
✅ Files skipped from review due to trivial changes (1)
- workers/main/src/configs/weeklyFinancialReport.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- workers/main/src/services/WeeklyFinancialReport/IWeeklyFinancialReportRepository.ts
🧰 Additional context used
🧬 Code Graph Analysis (3)
workers/main/src/services/WeeklyFinancialReport/GroupAggregator.ts (1)
workers/main/src/common/types.ts (1)
TargetUnit(3-14)
workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportFormatter.ts (2)
workers/main/src/common/formatUtils.ts (1)
formatCurrency(1-3)workers/main/src/configs/weeklyFinancialReport.ts (2)
HIGH_MARGINALITY_THRESHOLD(6-6)MEDIUM_MARGINALITY_THRESHOLD(7-7)
workers/main/src/services/WeeklyFinancialReport/MarginalityCalculator.ts (1)
workers/main/src/configs/weeklyFinancialReport.ts (2)
HIGH_MARGINALITY_THRESHOLD(6-6)MEDIUM_MARGINALITY_THRESHOLD(7-7)
🪛 Biome (1.9.4)
workers/main/src/services/WeeklyFinancialReport/GroupAggregator.ts
[error] 3-15: Avoid classes that contain only static members.
Prefer using simple functions instead of classes with only static members.
(lint/complexity/noStaticOnlyClass)
workers/main/src/services/WeeklyFinancialReport/MarginalityCalculator.ts
[error] 19-47: Avoid classes that contain only static members.
Prefer using simple functions instead of classes with only static members.
(lint/complexity/noStaticOnlyClass)
[error] 23-23: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 24-24: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 42-42: Useless case clause.
because the default clause is present:
Unsafe fix: Remove the useless case.
(lint/complexity/noUselessSwitchCase)
⏰ Context from checks skipped due to timeout of 90000ms (5)
- GitHub Check: Docker Security Scanning (n8n, Dockerfile.n8n, n8n-test:latest)
- GitHub Check: Docker Security Scanning (temporal, Dockerfile.temporal, temporal-test:latest)
- GitHub Check: Service Availability Check
- GitHub Check: SonarQube
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (1)
workers/main/src/services/WeeklyFinancialReport/WeeklyFinancialReportRepository.ts (1)
96-100: Group aggregation re-scans the entire arrayEven if the outer loop is kept, consider modifying
GroupAggregator.aggregateGroupto accept the pre-partitioned array for that group to avoid yet another full scan.
- Added a spacer constant to enhance the readability of the formatted report details. - Updated the formatting of the report summary to include the spacer for better alignment of marginality groups. - Ensured consistent indentation across all report sections, improving overall presentation. These changes enhance the clarity and visual structure of the weekly financial report output.
- Added test data for two new groups (Group C and Group D) in the WeeklyFinancialReportRepository tests. - Updated assertions to verify that the report summary and details include the new groups, ensuring comprehensive coverage of the report generation functionality. These changes enhance the test suite by validating the inclusion of all relevant groups in the weekly financial report output.
|



WeeklyFinancialReportRepositoryclass implementingIWeeklyFinancialReportRepositoryfor generating weekly financial reports based on target units, employees, and projects.IWeeklyFinancialReportRepositoryinterface andGenerateReportInputtype for structured input handling.These changes enhance the financial reporting capabilities of the application, providing structured and detailed insights into weekly performance.